//
//  UIButton+ACButtonImageCach.m
//  MonitoringSystem
//
//  Created by JiaKang.Zhong on 16/5/3.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "UIButton+ACButtonImageCach.h"


@implementation UIButton (ACButtonImageCach)

+ (void)buttonWithImageCach:(UIButton *)obj andImageUrl:(NSString *)url{
    // 判断是否存在此图片
      NSString * imagePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:[NSString stringWithFormat:@"/%@",url]];
    UIImage * isExitObj = [UIImage imageWithContentsOfFile:imagePath];
    if (isExitObj) {
        NSLog(@"存在，直接加到按钮上");
        [obj setImage:isExitObj forState:UIControlStateNormal];
    }
    else{
        NSLog(@"不存在，开始下载");
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
  
            NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[IMAGEURL stringByAppendingString:url]]];
            NSLog(@"下载url:%@",[IMAGEURL stringByAppendingString:url]);
            UIImage * image = [UIImage imageWithData:data];
            dispatch_async(dispatch_get_main_queue(), ^{
                 NSLog(@"下载完成，显示");
                // 写入到本地
                [data writeToFile:imagePath atomically:YES];
                 [obj setImage:image forState:UIControlStateNormal];
               
            });
            
        });
    }
    
}
@end
